import store from '@/store'
import base64 from '@/common/base64'

import { Message } from 'element-ui'
import nedb from '../../db/nedb'

let i = 0

// 会话列表推送 ok
function conversationPushNoticeHandle(msg) {
    Message({
        type: 'success',
        message: '会话列表已经更新',
        duration: 1000
    })
    let message = JSON.parse(msg.message)
    let wechatId = message.WeChatId
    if (message.Convers && message.Convers.length > 0) {
        // 更新会话
        store.dispatch('nedb/UpdateOrAddConversations', message)
    }
}

// 好友列表 ok
function friendPushNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (store.getters['conversation/freshDisabled']) {
        let count = message.Count || 0 // 好友数量
        let page = message.Page || 0
        let over = (page + 1) * 100 >= count
        // 如果有好友
        let userId = store.getters.userId
        let wechatId = message.WeChatId
        let friends = []
        for (const friend of message.Friends) {
            friend.Page = page
            friend.WeChatId = wechatId
            friend.userId = userId
            friends.push(friend)
        }
        store.dispatch('nedb/AddFriends', friends)
        // 有好友并且推送完成
        if (over) {
            Message({
                type: 'success',
                message: '好友列表推送完成',
                duration: 1000
            })
            store.commit('conversation/SET_FRESH_DISABLED', false)
        }
    }
}

// 微信收消息通知 ok
function friendTalkNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    // electron 新消息闪烁
    if (store.getters.currentMode === 'electron') {
        const { ipcRenderer } = window.require('electron')
        ipcRenderer.send('operations', 'newMsg')
    }
    // 公众号消息 不处理
    // let reg = /^gh_/
    // if (reg.test(message.FriendId)) return

    // 更新会话表
    store.dispatch('nedb/UpdateOrAddConversationsByTalk', message)
    // 消息插入nedb chats
    store.dispatch('nedb/AddChats', message)

    // 自动打招呼和自动回复,不考虑群聊
    if (
        message.FriendId.indexOf('@chatroom') === -1 &&
        message.FriendId.indexOf('im.chatroom') === -1
    ) {
        // 自动打招呼
        store.dispatch('nedb/AutoHi', message)
        // 自动回复
        store.dispatch('nedb/AutoReply', message)
    }
}

// 微信发信息通知 ok
function weChatTalkToFriendNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    message.IsSend = true
    // 有些消息没有msgSvrId 这里人为的添加一个
    // 如发红包消息
    if (!message.msgSvrId) {
        message.msgSvrId = message.CreateTime
    }
    // 更新会话表
    store.dispatch('nedb/UpdateOrAddConversationsByTalk', message)
    // 消息插入nedb chats
    store.dispatch('nedb/AddChats', message)
}

// 消息设为已读 ok
function postMessageReadNoticeHandle(msg) {
    // let message = JSON.parse(msg.message)
}

// 好友信息变更通知 ok
function friendAddNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (!message.Friend) return
    // 更新好友信息
    let newFriend = {}
    for (const key in message.Friend) {
        if (message.Friend.hasOwnProperty(key)) {
            newFriend[key] = message.Friend[key]
        }
    }
    newFriend.WeChatId = message.WeChatId
    newFriend.userId = store.getters.userId
    // 更新friends
    store.dispatch('nedb/UpdateFriendsByOne', newFriend)
    // 更新currentFriends
    // store.dispatch('conversation/UpdateCurrentFriends', newFriend)
}

// 发消息任务结果通知 ok
function talkToFriendTaskResultNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    // CreateTime: "1595239670640"
    // FriendId: "wxid_n5l57vd9fpf622"
    // MsgId: "15952396702835274"
    // MsgSvrId: "6406755845018185089"
    // Success: true
    // WeChatId: "wxid_9988ti1oz81g22"
    if (message.Success) {
        Message({
            type: 'success',
            message: '消息发送成功!',
            duration: 1000
        })
        // 更新会话列表
        nedb.chats.findOne({
            WeChatId: message.WeChatId,
            MsgId: message.MsgId,
        }, (err, doc) => {
            if (err) return
            store.dispatch('nedb/UpdateOrAddConversationsByTalk', doc)
        })
        // 更新
        store.dispatch('nedb/UpdateChats', message)
    } else {
        Message({
            type: 'error',
            message: `MsgId:${message.MsgId}发送失败`,
            duration: 1000,
        })
    }
}

// 标签新增|修改通知 ok
function contactLabelAddNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (message.Label) {
        store.dispatch('nedb/AddLabel', message)
    }
}

// 标签删除通知 ok
function contactLabelDelNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    store.dispatch('nedb/DeleteLabel', message)
}

// 历史消息推送 ok
function historyMsgPushNoticeHandle(msg) {
    let mj = JSON.parse(msg.message)
    store.dispatch('nedb/AddChatsByHistory', mj)
}

// 返回图片/视频/文件详情 ok
function requestTalkDetailTaskResultNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (message.Content && typeof message.Content === 'string') {
        store.commit('conversation/SET_URL', base64.decode(message.Content))
        // 更新本地chats的图片url
        store.dispatch('nedb/UpdateChatImgUrl', message)
    }
}

// 返回收红包/转账结果 ok
function takeMoneyTaskResultNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (message.Success) {
        Message({
            type: 'success',
            message: '打开红包成功！',
            duration: 1000
        })
    } else {
        Message({
            type: 'error',
            message: '打开红包失败！',
            duration: 2000
        })
        message.Amount = '打开红包失败！'
    }
    store.dispatch('nedb/UpdateLuckMoney', message)
}

// 查询红包结果 ok
function queryHbDetailTaskResultNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    store.commit('conversation/SET_HB_DETAIL_VISIBLE', true)
    store.commit('conversation/SET_HB_DETAIL', message)
}

// ===============================群聊相关===============================
//  群聊列表 ok
function chatroomPushNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    let count = message.Count || 0 // 好友数量
    let page = message.Page || 0
    let over = (page + 1) * 2 >= count
    // 有好友并且推送完成
    if (over) {
        Message({
            type: 'success',
            message: '群聊列表推送完成',
            duration: 1000
        })
        store.commit('conversation/SET_FRESH_DISABLED', false)
    }
    store.dispatch('nedb/AddChatRooms', message)
}

// 群成员信息 ok
function chatRoomMembersNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    i++
    setTimeout(() => {
        store.dispatch('nedb/AddOrUpdateChatRoomMembers', message)
        i--
    }, i * 500);

}

// 群聊新增通知 ok
// RequestChatRoomInfoTask的返回
function chatRoomAddNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (!message.ChatRoom) return
    store.dispatch('nedb/AddOrUpdateChatRoom', message)
}

// 群聊删除通知 ok
function chatRoomDelNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    store.dispatch('nedb/RemoveChatRoom', message)
}

// 群二维码 ok
function pullChatRoomQrCodeTaskResultNoticeHandle(msg) {
    let qrcode = JSON.parse(msg.message)
    if (qrcode.Success) {
        Message({
            type: 'success',
            message: '获取群二维码成功！',
            duration: 1000
        })
        store.dispatch('nedb/UpdateQrCode', qrcode)
    } else {
        Message({
            type: 'error',
            message: '获取群二维码失败！',
            duration: 2000
        })
    }
}

// 群聊信息变更通知 ok
function chatRoomChangedNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    if (!message.Content) return
    let sqlStr = {}

    let currentWeChatId = store.getters['conversation/currentWeChatId']
    let currentFriends = store.getters['conversation/currentFriends']
    let currentFriend = currentFriends[currentWeChatId]
    let currentFriendId = (currentFriend && currentFriend.UserName) ? currentFriend.UserName : ''

    let chatRoom = {
        WeChatId: message.WeChatId,
        UserName: message.UserName
    }
    if (message.UserName === currentFriendId) {
        for (const key in currentFriend) {
            if (currentFriend.hasOwnProperty(key)) {
                chatRoom[key] = currentFriend[key]
            }
        }
    }

    switch (message.What) {
        // 群聊名称 ok
        case 'Change_NickName':
            sqlStr = { NickName: message.Content }
            chatRoom.NickName = message.Content
            break
        // 公告 ok 群聊里 remark 用来存公告
        case 'Change_PublicNotice':
            sqlStr = { Notice: message.Content }
            chatRoom.Notice = message.Content
            break
        // 群显示名 ok
        case 'Change_ShowName':
            {
                let reg = /[a-zA-z0-9_]{6,20}=/g
                let wechatIds = message.Content.match(reg)
                let wechatIds2 = wechatIds.map(function (id) {
                    return id.replace(/=/, '')
                })

                let names = message.Content.replace(/{|}/gi, '').split(/[a-zA-z0-9_]{6,20}=/)
                let names2 = names.filter(function (s) {
                    return s && s.trim();
                });
                let nc = []
                for (let index = 0; index < names2.length; index++) {
                    nc.push({ UserName: wechatIds2[index], ShowName: names2[index] })
                }
                sqlStr = { ShowNameList: nc }
                chatRoom.ShowNameList = nc
            }
            break
        // 自己的群显示名 ok
        case 'Change_MyShowName':
            sqlStr = { SelfDisplayName: message.Content }
            chatRoom.SelfDisplayName = message.Content
            break
        // 改变群主 ok
        case 'Change_Owner':
            sqlStr = { Owner: message.Content }
            chatRoom.Owner = message.Content
            break
        // 改变群头像 ok
        case 'Change_Avatar':
            sqlStr = { Avatar: message.Content }
            chatRoom.Avatar = message.Content
            break
        // 群成员修改 ok
        default:
            {
                sqlStr = { Avatar: message.Content }
                let membersList = message.Content.split(';')
                sqlStr = { MemberList: membersList }
                chatRoom.MemberList = membersList
            }
            break
    }
    message.sqlStr = sqlStr
    // 更新群聊
    store.dispatch('nedb/UpdateChatRoom', message)
    // 更新currentFriends
    if (message.UserName === currentFriendId) {
        let fmsg = {
            wechatId: message.WeChatId,
            friend: chatRoom
        }
        store.commit('conversation/SET_CURRENT_FRIENDS', fmsg)
    }
}

// 删除好友通知 ok
function friendDelNoticeHandle(msg) {
    let message = JSON.parse(msg.message)
    store.dispatch('nedb/RemoveFriend', message)
}

export default {
    conversationPushNoticeHandle,
    friendPushNoticeHandle,
    chatroomPushNoticeHandle,
    friendAddNoticeHandle,
    contactLabelAddNoticeHandle,
    contactLabelDelNoticeHandle,
    friendDelNoticeHandle,
    friendTalkNoticeHandle,
    postMessageReadNoticeHandle,
    takeMoneyTaskResultNoticeHandle,
    queryHbDetailTaskResultNoticeHandle,
    talkToFriendTaskResultNoticeHandle,
    requestTalkDetailTaskResultNoticeHandle,
    chatRoomDelNoticeHandle,
    chatRoomAddNoticeHandle,
    chatRoomChangedNoticeHandle,
    chatRoomMembersNoticeHandle,
    pullChatRoomQrCodeTaskResultNoticeHandle,
    weChatTalkToFriendNoticeHandle,
    historyMsgPushNoticeHandle,
}
